﻿var PageSize = 25;
var grid = null;
var url = "UserInf.aspx?";
var permission = null;
var role = null;

$(document).ready(function () {
    permission = JSON.parse($("#hdPermission").val());
    role = JSON.parse($("#hdRole").val());
    grid = $("#maingrid").ligerGrid({
        columns: [
            { display: '用户ID', name: 'UserID', width: 100, type: 'string', align:'left', isSort: true },
            { display: '用户名称', name: 'Name', width: 120, align: 'left' },
            { display: '角色', name: 'RoleList', width: 300, align: 'left', isSort: false,
                editor: { type: 'select', valueField: 'RoleID', textField: 'RoleDesc', data: role, valueColumnName: 'RoleList', p: { isShowCheckBox: true, isMultiSelect: true, split: '/', width: 245, render: function (value, text) { return value; } } }
            },
            { display: '8ID', name: 'EightID', width: 100, align: 'center' },
            { display: '邮箱', name: 'Email',  width: 150, align: 'left' },
            { display: '更新时间', name: 'Lpt', width: 120, align: 'left', isSort: false },
            { display: '操作者', name: 'Whom', width: 100, align: 'left', isSort: false }
            ],
            pageSize: PageSize, width: '100%', pageSizeOptions: [3,20, 25, 30, 35], height: '99%',
            pageStatMessage: 'Record:{from}-{to} Total:{total} Page Size:{pagesize}',
        checkbox: true, url: url + 'Action=GetData', sortName: 'rID', dataAction: 'local', toolbar: {},enabledEdit: true,
        rowAttrRender: function (item, rowid) {
            var color = ""; if (item.Flag == "I") color = " my-disabled"; return color;
        },
        onDblClickRow: function (row, rowindex, rowDomElement) {
            if (permission.isEdit) {
                ShowDetail({
                    RID: row.RID,
                    UserID: row.UserID,
                    Name: row.Name,
                    RoleList: row.RoleList,
                    EightID: row.EightID,
                    Email: row.Email,
                    Flag: row.Flag
                }); 
                    }
        }
    });

    loadToolbar();
    InitForm();
});

function loadToolbar() {
    var griditems = [];

    if (permission.isEdit) {
        griditems[griditems.length] = { click: toolbarClick, text: "保存", img: "../images/Save.ico", id: "Save" };
        griditems[griditems.length] = { click: toolbarClick, text: "新增", img: "../images/add.png", id: "Add" };
    }
    if (permission.isActive) 
        griditems[griditems.length] = { click: toolbarClick, text: "生效", img: "../images/Active.png", id: "Enable" };
    if (permission.isInactive) 
        griditems[griditems.length] = { click: toolbarClick, text: "失效", img: "../images/Frozen.png", id: "Disable" };
    grid.toolbarManager.set('items', griditems);
}

function InitForm() {
    $("#txtKey").ligerTextBox({ label: "用户ID/名称", labelWidth: 100 });
    $("#BtnSearch").click(function () { BtnSearch_Click(); });
}

//工具条事件
function toolbarClick(item) {
    switch (item.id) {
        case "Add": BtnAdd_Click(); break;
        case "Enable": BtnEnable_Click(); break;
        case "Disable": BtnDisable_Click(); break;
        case "Save": BtnSave_Click(); break;
    }
}

function BtnSearch_Click() {
    grid.options.newPage = 1;
    grid.set('parms', { where: $("#txtKey").val() });
    grid.loadData();
}

function BtnAdd_Click() { ShowDetail(null); }

function BtnEnable_Click() { ProcessData("A"); }

function BtnDisable_Click() { ProcessData("I"); }

//保存
function BtnSave_Click() {
    var rids = GetSaveUserIDandRole();
    if (rids != "") {
        $.ajax({
            url: url, dataType: "text", cache: false, data: { Action: 'SetRole', rids: rids },
            success: function (msg) { if (msg == "") { BtnSearch_Click(); toastrSuccess("Processed successfully/处理成功!"); } else { toastrError("Processed Failed/处理失败!<br/>" + msg) } },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                ShowError("BtnSave_Click()", XMLHttpRequest, textStatus, errorThrown);
            }
        });
    }
}

function ProcessData(type) {
    var rids = GetClientRID();
    if (rids != "") {
        $.ajax({
            url: url, dataType: "text", cache: false, data: { Action: 'Process', type: type, rids: rids },
            success: function (msg) { if (msg == "") { toastrSuccess("Processed successfully/处理成功!"); BtnSearch_Click(); } else { toastrError("Processed Failed/处理失败!<br/>" + msg) } },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                ShowError("ProcessData()", XMLHttpRequest, textStatus, errorThrown);
            }
        });
    }
}

function GetClientRID() {
    var rows = grid.getSelectedRows();
    if (!rows.length) { toastrWarning('Please select lines to be processed!<br/>请选择操作记录!'); return ""; }
    var ids = [];
    for (var i = 0; i < rows.length; i++) ids.push(rows[i].RID);
    return ids.join(',');
}


function GetSaveUserIDandRole() {//获取UserID和RoleList,用'*'分隔
    var rows = grid.getSelectedRows();
    if (!rows.length) { toastrWarning('Please select lines to be processed!<br/>请选择操作记录!'); return ""; }
    for (i = 0; i < rows.length; i++) {
        grid.endEdit(rows[i]);
    }
    rows = grid.getSelectedRows();
    var ids = [];
    for (i = 0; i < rows.length; i++) {
        var roles = rows[i].RoleList.split('/');  //$("#RoleList_" + rows[i].RID).val().split('/');
        var type = "";
        for (var j = 0; j < roles.length; j++) {
            for (var k = 0; k < role.length; k++) {
                if (roles[j] == role[k].value) {
                    type = role[k].type;
                }
            }
        }
        if (rows[i].Flag == "A")//有效的才修改
            ids.push(rows[i].UserID + "*" + rows[i].RoleList);
    }

    return ids.join(',');
}

////////////////////////////////////////////
//新增、编辑框
var detailWin = null, curentData = null;

function ShowDetail(data) {
    curentData = data;
    if (detailWin) {
        detailWin.show();
    }
    else {
        //创建表单结构
        var mainform = $("#mainform");
        mainform.ligerForm({
            inputWidth: 250, labelWidth: 120,
            fields: [
                { name: "RID", type: "hidden" },
                { name: "Flag", type: "hidden" },
                { display: '用户ID', name: 'TxtUserID', newline: true, type: 'text',prefixID:'K' },
                { display: '用户名称', name: 'TxtName', newline: true, type: 'text' },
                { display: '角色', name: "CbRLID", newline: true, type: "select", align: 'left', comboboxName: "RDesc", options: { valueField: 'RoleID', textField: 'RoleDesc', data: role, isMultiSelect: true, split: '/', render: function (value, text) { return value; } } },
                { display: '邮箱', name: 'TxtEmail', newline: true, type: 'text' },
                { display: '8ID', name: 'TxtEightID', newline: true, type: 'text' }
            ]
        });

        detailWin = $.ligerDialog.open({
            title: "用户管理", allowClose: false, target: $("#detail"), width: 450, height: 250, top: 120,
            buttons: [{ text: '保存', onclick: function () { save(); } }, { text: '取消', onclick: function () { detailWin.hide(); HideTip(); } }]
        });
    }

    ClearEdit();

    $("#TxtEightID").attr("onkeyup", 'this.value=this.value.replace(/\\D/g,\"\")');
    $("#TxtEightID").attr("onblur", 'this.value=this.value.replace(/\\D/g,\"\")');

    if (curentData != null) {
        if (curentData.RID != '')
            $("#RDesc").ligerComboBox().selectValue(curentData.RoleList);
        else
            $("#RDesc").ligerComboBox().selectValue('');
        $("#RID").val(curentData.RID);
        $("#Flag").val(curentData.Flag);
        var cc = $("#TxtUserID");
        $("#TxtUserID").val(curentData.UserID);
        $("#TxtUserID").ligerGetTextBoxManager().setDisabled();
        $("#TxtName").val(curentData.Name);
        $("#TxtEmail").val(curentData.Email);
        $("#TxtEightID").val(curentData.EightID);
        $("#TxtName").focus();
    } else {
        $("#RDesc").ligerComboBox().selectValue('');
        $("#RID").val('');
        $("#Flag").val('A');
        $("#TxtUserID").val('');
        $("#TxtUserID").ligerGetTextBoxManager().setEnabled();
        $("#TxtName").val('');
        $("#TxtEmail").val('');
        $("#TxtEightID").val('');
        $("#TxtUserID").focus();
    }
    $("#TxtUserID").attr("maxlength", 30);
    $("#TxtName").attr("maxlength", 50);
    $("#TxtEmail").attr("maxlength", 320);
    $("#TxtEightID").attr("maxlength", 8);

    function save() {
        HideTip();
        curentData = curentData || {};
        curentData.RID = $("#RID").val();
        curentData.UserID = $.trim($("#TxtUserID").val()); //UserID
        if (curentData.UserID == "") { $("#TxtUserID").ligerTip({ content: "Empty is not allowed/不能为空!" }); $("#TxtUserID").select(); return; }
        else if (curentData.UserID.length > 30) { $("#TxtUserID").ligerTip({ content: "Max allowed should be 30/最大长度为30!" }); $("#TxtUserID").select(); return; }


        curentData.Name = $.trim($("#TxtName").val());//Name
        if (curentData.Name == "") { $("#TxtName").ligerTip({ content: "Empty is not allowed/不能为空!" }); $("#TxtName").select(); return; }
        else if (curentData.Name.length > 50) { $("#TxtName").ligerTip({ content: "Max allowed should be 50/最大长度为50!" }); $("#TxtName").select(); return; }


        curentData.RoleList = $("#CbRLID").val();//Role
        curentData.Email = $.trim($("#TxtEmail").val());//Email
        if (curentData.Email == "") { $("#TxtEmail").ligerTip({ content: "Empty is not allowed/不能为空!" }); $("#TxtEmail").select(); return; }
        else if (curentData.Email.length > 320) { $("#TxtEmail").ligerTip({ content: "Max allowed should be 320/最大长度为320!" }); $("#TxtEmail").select(); return; }
        else if (!checkMail(curentData.Email)) { $("#TxtEmail").ligerTip({ content: "Email format error/邮箱地址格式错误!" }); $("#TxtEmail").select(); return; }

        curentData.EightID = $.trim($("#TxtEightID").val()); //8ID
        if (curentData.EightID.length > 0 && curentData.EightID.length != 8) {
            $("#TxtEightID").ligerTip({ content: "Please enter the eight digit number/请输入8位数字!" }); $("#TxtEightID").select(); return;
        }
        curentData.Flag = $("#Flag").val();//Flag
        $.ajax({
            cache: false, url: url + 'Action=Save', data: curentData, dataType: 'text', cache: false,
            success: function (message) {
                if (message == "") { BtnSearch_Click(); toastrSuccess('Saved/保存成功!'); detailWin.hide(); }
                else { toastrError('Error! Save failed/保存失败!<br/>' + message); }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                ShowError("Save()", XMLHttpRequest, textStatus, errorThrown);
            }
        });

    }

    function HideTip() {
        $("#TxtUserID").ligerHideTip();
        $("#TxtName").ligerHideTip();
        $("#TxtEmail").ligerHideTip();
        $("#TxtEightID").ligerHideTip();
    }

    function ClearEdit() {
        $("#RID").val("");
        $("#TxtUserID").val("");
        $("#TxtName").val("");
        $("#TxtEmaila").val("");
        $("#TxtEightID").val("");
    }
}
/////////////////////////////////////////////////////////
function ShowError(fun, XMLHttpRequest, textStatus, errorThrown) {
    var mess = "出错了! 请联系管理员";
    mess += "function:" + fun + "<br/>";
    mess += "XMLHttpRequest.status:" + XMLHttpRequest.status + "<br/>";
    mess += "XMLHttpRequest.readyState:" + XMLHttpRequest.readyState + "<br/>";
    mess += "textStatus:" + textStatus;
    toastrError(mess);
}

/**
* [checkMail description] 检查邮件格式
* @param  {[type]} email [description]
* @return {[type]}       [description]
*/
function checkMail(email) {
    var filter = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    if (filter.test(email)) {
        return true;
    }
    return false;
}

